package com.x.config;

/**
 * ClassName: JavaConfiguration
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.03 16:31
 */

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * Java配置类，代替xml配置文件
 *  1、扫描包
 *  2、引用配置文件
 *  3、声明第三方依赖的组件
 */

@Configuration //声明该类为配置类
@ComponentScan(value = {"com.x.ioc_01"}) //1、扫描包, 可写多个
@PropertySource(value = "classpath:jdbc.properties") //2、引入配置文件
public class JavaConfiguration {

    @Value("${com.x.url}")
    private String url;

    @Value("${com.x.driver}")
    private String driver;

    @Value("${com.x.username}")
    private String username;

    @Value("${com.x.password}")
    private String password;

    //3、声明第三方依赖的组件

    //Druid
    @Bean(name = "source1")
    public DruidDataSource dataSource1(){
        DruidDataSource dataSource = new DruidDataSource();

        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    @Bean(name = "source2")
    public DruidDataSource dataSource2(){
        DruidDataSource dataSource = new DruidDataSource();

        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }


    //JdbcTemplate  -> Druid
    @Bean
    public JdbcTemplate jdbcTemplate(DruidDataSource source1){ //这里的形参可以用上方多个Druid对象在Bean注解中的别名
        JdbcTemplate jdbcTemplate = new JdbcTemplate();

        //需要dataSource: 需要ioc的外部依赖组件时
            //如果其他组件也是@Bean方法，则可以直接调用。如此处的dataSource()类
            //jdbcTemplate.setDataSource(dataSource());
            //也可以设置在形参中
            jdbcTemplate.setDataSource(source1);


        return jdbcTemplate;
    }


}
